package com.ssish.saas.eccs.service;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.ssish.saas.eccs.common.BaseResult;
import com.ssish.saas.eccs.constant.db.vo.ocr.Configure;
import com.ssish.saas.eccs.constant.db.vo.ocr.ItemDetailInfo;
import com.ssish.saas.eccs.constant.db.vo.ocr.ItemInfo;
import com.ssish.saas.eccs.constant.db.vo.ocr.Items;
import com.ssish.saas.eccs.constant.db.vo.ocr.OcrRequestVo;
import com.ssish.saas.eccs.constant.db.vo.ocr.OcrResponseDto;
import com.ssish.saas.eccs.currency.ReturnMsg;

@Service
public class OrcApiService {
    public static final String UTF_8 = "UTF-8";
    public static final String APP_CODE = "993a2616a62a486a87741874b24a6c07";
    public static final String OCR_URL = "https://ocrdiy.market.alicloudapi.com/api/predict/ocr_sdt";

    public BaseResult<OcrResponseDto> getOcrResponseDtoFromOcr(OcrRequestVo ocrRequestVo) {

        System.out.println("start");
        String result = getOcrResult(ocrRequestVo);
        OcrResponseDto t = null;
        try {
            t = JSONObject.parseObject(result, OcrResponseDto.class);
        } catch (Exception e) {
            t = new OcrResponseDto();
        } 
        if(!t.isSuccess()){
            return new BaseResult<OcrResponseDto>(ReturnMsg.UNKONOW_ERROR.getCode(), result, null);
        }
        System.out.println("end");
        return new BaseResult<OcrResponseDto>(ReturnMsg.SUCCESS.getCode(), ReturnMsg.SUCCESS.getMsg(), valOcrResponseDto(t));
    }

    public OcrResponseDto valOcrResponseDto(OcrResponseDto ocrResponseDto){
        Items item = ocrResponseDto.getItems();
        List<List<String>> Table1 = item.getTable1();
        
        
        List<ItemInfo> itemInfoList  = new ArrayList<ItemInfo>();
        ItemInfo itemInfo = null;
        List<ItemDetailInfo> itemDetailInfoList = null;

        ItemDetailInfo itemDetailInfo = null;
        int current = 0;
        for(List<String> list:Table1){
            if(null == list || list.size()!=8){
                continue;
            }
            String serviceDate = list.get(0);
            String itemCode = list.get(1);
            String feeDetail = list.get(2);
            String comPany = list.get(3);
            String unitPrice = list.get(4);
            String discount = list.get(5);
            String itemPaidAmount = list.get(6);
            String totalPrice = list.get(7);
            if(StringUtil.isNotEmpty(feeDetail)&&StringUtil.isNotEmpty(totalPrice)&&StringUtil.isEmpty(serviceDate)&&StringUtil.isEmpty(itemCode)
                &&StringUtil.isEmpty(comPany)&&StringUtil.isEmpty(unitPrice)&&StringUtil.isEmpty(discount)&&StringUtil.isEmpty(itemPaidAmount)){
                itemInfo = new ItemInfo();
                itemInfo.setBenefitDesc(feeDetail);
                itemInfo.setBenefitAmount(totalPrice);
                itemDetailInfoList = new ArrayList<ItemDetailInfo>();
                itemInfo.setItemDetailInfoList(itemDetailInfoList);
                itemInfoList.add(itemInfo);
                current ++;
                continue;
            }
            if(StringUtil.isNotEmpty(serviceDate)&&StringUtil.isNotEmpty(itemCode)&&StringUtil.isNotEmpty(feeDetail)&&StringUtil.isNotEmpty(comPany)
                &&StringUtil.isNotEmpty(unitPrice)&&StringUtil.isNotEmpty(totalPrice)){
                itemDetailInfo = new ItemDetailInfo();
                itemDetailInfo.setServiceDate(serviceDate);
                itemDetailInfo.setItemCode(itemCode);
                itemDetailInfo.setFeeDetail(feeDetail);
                itemDetailInfo.setComPany(comPany);
                itemDetailInfo.setUnitPrice(unitPrice);
                itemDetailInfo.setTotalPrice(totalPrice);
                if(0 == current){
                    continue;
                }
                itemInfoList.get(current-1).getItemDetailInfoList().add(itemDetailInfo);
            }
        }
        
        item.setItemInfoList(itemInfoList);
        
        
        
        if(StringUtil.isNotEmpty(item.getPrimaryDiagnosis())&&item.getPrimaryDiagnosis().indexOf(" ")!=-1){
            String [] primaryDiagnosiss = item.getPrimaryDiagnosis().split(" ");
            int length = 3;
            if(primaryDiagnosiss.length<3){
                length = primaryDiagnosiss.length;
            }
            if(length>2){
                item.setTheThirdDiagnosis(primaryDiagnosiss[2]);  
                item.setSecondDiagnosis(primaryDiagnosiss[1]);
            }else if(length>1){
                item.setSecondDiagnosis(primaryDiagnosiss[1]);
            }
            item.setPrimaryDiagnosis(primaryDiagnosiss[0]);
        }
        
        
        item.setTable1(null);
        ocrResponseDto.setItems(item);
        System.out.println(JSON.toJSONString(ocrResponseDto));
        return ocrResponseDto;
    }
    
    
    
    
    
    public static void main(String[] args) {
        OcrRequestVo ocrRequestVo = new OcrRequestVo();
        ocrRequestVo.setImage(getImgStr("D:\\1006.jpg"));
        Configure configure = new Configure();
        List<String> template_list = new ArrayList<String>();
        template_list.add("a6720c74-823d-44a9-8036-9755ed9e6ad31577432536");
        configure.setTemplate_list(template_list);
        ocrRequestVo.setConfigure(configure);
        String result = getOcrResult(ocrRequestVo);
        OcrResponseDto t = null;
        try {
            t = JSONObject.parseObject(result, OcrResponseDto.class);
        } catch (Exception e) {
            t = new OcrResponseDto();
        } 

        if(!t.isSuccess()){

            System.out.println(t.isSuccess());
        }
//        System.out.println(JSON.toJSONString(valOcrResponseDto(t)));
        System.out.println(result);
        
    }
    public static String getOcrResult(OcrRequestVo ocrRequestVo) {
        
        Map<String, String> headers = new HashMap<String, String>();
        // 最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + APP_CODE);
        // 根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");

        String json = JSON.toJSONString(ocrRequestVo);
        System.out.println(json);
        String result = "";
        try {
            System.out.println(json);
            result = sendPost(OCR_URL, 5000, 5000, headers, null, json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String sendPost(String url, int socketTimeout, int connectTimeout, Map<String, String> headers,
        Map<String, ?> params, String json) throws Exception {
        // URL处理: 请求参数拼接到URL中传递
        if (null != params && params.size() != 0) {
            List<NameValuePair> list = new ArrayList<>();
            for (Entry<String, ?> entry : params.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
            }
            String uri = EntityUtils.toString(new UrlEncodedFormEntity(list, UTF_8));
            if (uri != null) {
                url = url.contains("?") ? (url + "&" + uri) : (url + "?" + uri);
            }
        }

        // 构建请求: HttpPost
        HttpPost post = new HttpPost(url);
        RequestConfig config =
            RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout)
                .setConnectionRequestTimeout(connectTimeout).build();
         post.setConfig(config);

        // 设置请求头: Header
        if (null != headers && headers.size() != 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                post.addHeader(entry.getKey(), entry.getValue());
            }
        }

        // 设置请求体: HttpEntity
        if (null != json && !"".equals(json.trim())) {
            post.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
        }

        // 调用并返回结果
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClients.createDefault();
            response = client.execute(post);
            return EntityUtils.toString(response.getEntity(), UTF_8);
        } finally {
            if (response != null) {
                response.close();
            }
            if (client != null) {
                client.close();
            }
        }
    }
    public static String getImgStr(String imgFile) {
        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理

        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(Base64.encodeBase64(data));
    }
}
